// player.js
class VideoPlayer {
    constructor() {
        this.canvas = document.getElementById('videoCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.startBtn = document.getElementById('startBtn');
        this.pauseBtn = document.getElementById('pauseBtn');
        this.stopBtn = document.getElementById('stopBtn');
        this.statusText = document.getElementById('statusText');
        this.latencyEl = document.getElementById('latency');
        this.fpsEl = document.getElementById('fps');

        this.ws = null;
        this.img = new Image();
        this.frameTimes = [];
        this.lastFrameTime = 0;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectDelay = 1000;
        this.reconnectTimeout = null;
        this.isStreaming = false;
        this.isPaused = false;

        this.initCanvas();
        this.setupEventListeners();
        this.startFpsCounter();
    }

    initCanvas() {
        // 设置Canvas尺寸为1280x720，保持16:9比例
        const aspectRatio = 16 / 9;
        const maxWidth = window.innerWidth * 0.9;
        const maxHeight = window.innerHeight * 0.7;

        let width = maxWidth;
        let height = width / aspectRatio;

        if (height > maxHeight) {
            height = maxHeight;
            width = height * aspectRatio;
        }

        this.canvas.width = width;
        this.canvas.height = height;
    }

    setupEventListeners() {
        this.startBtn.addEventListener('click', () => this.startStreaming());
        this.pauseBtn.addEventListener('click', () => this.togglePause());
        this.stopBtn.addEventListener('click', () => this.stopStreaming());

        window.addEventListener('resize', () => this.initCanvas());
        window.addEventListener('beforeunload', () => this.disconnect());
    }

    // 开始视频流播放
    async startStreaming() {
        try {
            // 重置状态
            this.clearReconnectTimeout();
            this.reconnectAttempts = 0;
            this.isStreaming = true;
            this.isPaused = false;

            this.updateStatus('正在启动视频流...', 'orange');
            this.startBtn.disabled = true;
            this.pauseBtn.disabled = true;
            this.stopBtn.disabled = true;

            // 调用后端API开始流传输
            const response = await fetch('/rtsp/api/start', {
                method: 'POST'
            });

            if (response.ok) {
                this.updateStatus('视频流已启动', 'green');
                // 建立WebSocket连接以接收视频帧
                this.connect();
                this.pauseBtn.disabled = false;
                this.stopBtn.disabled = false;
            } else {
                const errorMessage = await response.text();
                throw new Error('启动流失败: ' + errorMessage);
            }
        } catch (error) {
            console.error('启动流失败:', error);
            this.updateStatus('启动失败: ' + error.message, 'red');
            this.startBtn.disabled = false;
            this.pauseBtn.disabled = true;
            this.stopBtn.disabled = true;
            this.isStreaming = false;
        }
    }

    // 切换暂停/恢复状态
    async togglePause() {
        try {
            if (this.isPaused) {
                // 恢复播放
                const response = await fetch('/rtsp/api/resume', {
                    method: 'POST'
                });

                if (response.ok) {
                    this.isPaused = false;
                    this.pauseBtn.textContent = '暂停';
                    this.updateStatus('正在播放', 'green');
                } else {
                    throw new Error('恢复流失败');
                }
            } else {
                // 暂停播放
                const response = await fetch('/rtsp/api/pause', {
                    method: 'POST'
                });

                if (response.ok) {
                    this.isPaused = true;
                    this.pauseBtn.textContent = '恢复';
                    this.updateStatus('已暂停', 'orange');
                } else {
                    throw new Error('暂停流失败');
                }
            }
        } catch (error) {
            console.error('切换暂停状态失败:', error);
            this.updateStatus('操作失败: ' + error.message, 'red');
        }
    }

    // 停止视频流播放
    async stopStreaming() {
        try {
            this.isStreaming = false;
            this.isPaused = false;
            this.updateStatus('正在停止视频流...', 'orange');
            this.startBtn.disabled = true;
            this.pauseBtn.disabled = true;
            this.stopBtn.disabled = true;

            // 先断开WebSocket连接
            this.disconnect();

            // 调用后端API停止流传输
            const response = await fetch('/rtsp/api/stop', {
                method: 'POST'
            });

            if (response.ok) {
                this.updateStatus('视频流已停止', 'gray');
            } else {
                const errorMessage = await response.text();
                throw new Error('停止流失败: ' + errorMessage);
            }
        } catch (error) {
            console.error('停止流失败:', error);
            this.updateStatus('停止失败: ' + error.message, 'red');
        } finally {
            this.startBtn.disabled = false;
            this.pauseBtn.disabled = true;
            this.stopBtn.disabled = true;
            this.pauseBtn.textContent = '暂停';
        }
    }

    connect() {
        // 清理之前的重连尝试
        this.clearReconnectTimeout();

        // 只有在流启动状态下才连接
        if (!this.isStreaming) {
            return;
        }

        if (this.ws && (this.ws.readyState === WebSocket.CONNECTING ||
            this.ws.readyState === WebSocket.OPEN)) {
            return;
        }

        this.updateStatus('正在连接WebSocket...', 'orange');

        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const host = window.location.host;
        const path = '/rtsp/video-stream';
        const wsUrl = `${protocol}//${host}${path}`;

        this.ws = new WebSocket(wsUrl);
        this.ws.binaryType = 'arraybuffer';

        this.ws.onopen = () => {
            this.updateStatus(this.isPaused ? '已暂停' : '正在播放', this.isPaused ? 'orange' : 'green');
            this.reconnectAttempts = 0;
            this.startBtn.disabled = true;
            this.pauseBtn.disabled = false;
            this.stopBtn.disabled = false;
        };

        this.ws.onmessage = (event) => {
            // 如果已暂停，忽略接收到的帧
            if (this.isPaused) return;

            const receiveTime = Date.now();
            const blob = new Blob([event.data], { type: 'image/jpeg' });
            const url = URL.createObjectURL(blob);

            this.img.onload = () => {
                this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
                this.ctx.drawImage(this.img, 0, 0, this.canvas.width, this.canvas.height);
                URL.revokeObjectURL(url);

                // 计算延迟
                const latency = Date.now() - receiveTime;
                this.latencyEl.textContent = latency;

                // 记录帧时间
                const now = performance.now();
                this.frameTimes.push(now);
                this.lastFrameTime = now;
            };

            this.img.onerror = () => {
                console.error('图片加载失败');
                URL.revokeObjectURL(url);
            };

            this.img.src = url;
        };

        this.ws.onclose = (event) => {
            this.updateStatus('WebSocket已断开', 'red');

            // 只有在流仍在运行且需要重连时才尝试重连
            if (this.isStreaming && this.reconnectAttempts < this.maxReconnectAttempts) {
                this.reconnectTimeout = setTimeout(() => {
                    this.reconnectAttempts++;
                    this.connect();
                }, this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1));
            } else if (!this.isStreaming) {
                // 如果流已停止，确保按钮状态正确
                this.startBtn.disabled = false;
                this.pauseBtn.disabled = true;
                this.stopBtn.disabled = true;
            } else {
                // 重试次数用完
                this.updateStatus('连接失败，重试次数已用完', 'red');
                this.startBtn.disabled = false;
                this.pauseBtn.disabled = true;
                this.stopBtn.disabled = true;
            }
        };

        this.ws.onerror = (error) => {
            console.error('WebSocket错误:', error);
            this.ws.close();
        };
    }

    disconnect() {
        // 标记流已停止
        this.isStreaming = false;
        this.isPaused = false;

        // 清理重连计时器
        this.clearReconnectTimeout();

        // 重置重连计数
        this.reconnectAttempts = 0;

        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.updateStatus('已停止', 'gray');
        this.startBtn.disabled = false;
        this.pauseBtn.disabled = true;
        this.stopBtn.disabled = true;
        this.pauseBtn.textContent = '暂停';
    }

    // 清理重连计时器的辅助方法
    clearReconnectTimeout() {
        if (this.reconnectTimeout) {
            clearTimeout(this.reconnectTimeout);
            this.reconnectTimeout = null;
        }
    }

    updateStatus(text, color) {
        this.statusText.textContent = text;
        this.statusText.style.color = color;
    }

    startFpsCounter() {
        setInterval(() => {
            const now = performance.now();
            // 移除1秒前的帧记录
            while (this.frameTimes.length > 0 &&
            (now - this.frameTimes[0]) > 1000) {
                this.frameTimes.shift();
            }

            // 计算FPS
            const fps = this.frameTimes.length;
            this.fpsEl.textContent = fps;

        }, 1000);
    }
}

// 初始化播放器
document.addEventListener('DOMContentLoaded', () => {
    const player = new VideoPlayer();
});
